package com.ycsj.goldmedalnewconcept.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mob.MobSDK;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.activity.AnswerListDetailsActivity.TimingReceiver;
import com.ycsj.goldmedalnewconcept.bean.FuxiExeQuelistDetail;
import com.ycsj.goldmedalnewconcept.bean.FuxiExedetaillistDetail;
import com.ycsj.goldmedalnewconcept.bean.FuxiExercisesBean;
import com.ycsj.goldmedalnewconcept.bean.UploadScoreBean;
import com.ycsj.goldmedalnewconcept.bean.timeresq;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;

@SuppressLint({ "HandlerLeak", "NewApi" })
public class WordFuxiAndroidActivity extends Activity implements
		OnClickListener {

	// private CheckBox cb_fuxi_collect;
	private ImageView iv_content;
	private int question_num = 0; // 当前题目集合角标
	private int score = 0; // 成绩
	private int p; // 点击位置
	private int Click = 1; // 点击次数
	private int ClickType1; // 点击类型
	private int ClickType2; // 点击类型
	private int alltrue = 0; // 题型2是否得分
	private String question_type; // 题型
	private int question_count; // 总数
	private TextView tv_word1;
	private TextView tv_word2;
	private String word1 = "";
	private String word2 = "";
	private MyHandler handler;
	private Button bt_check;
	private ImageView iv_horn_a;
	private ImageView iv_horn_b;
	// private TextView tv_question_content;
	private CheckBox cb_selecta;
	private CheckBox cb_selectb;
	private View rootview;
	private PopupWindow mPopWindow1;
	private PopupWindow mPopWindow2;
	private PopupWindow mPopWindow3;
	private GridView gv_match;
	private List<FuxiExeQuelistDetail> list;
	private List<FuxiExedetaillistDetail> detaillist;
	private List<Integer> dismissedlist;
	private LinearLayout ll_type1;
	private LinearLayout ll_type2;
	private ProgressBar progress_bar;
	private TextView tv_player;
	private TextView tv_player_img; // 喇叭图标
	private TextView tv_score;
	private TextView tv_pager;
	private TextView tv_text;
	private MatchAdapter mAdapter;
	private Message message4;
	private TextView tv_html_title;
	private TextView tv_word_back;
	private int lESSON_ID;
	private TextView tv_shoucang;
	ArrayList<UploadScoreBean> UploadScorelist = new ArrayList<UploadScoreBean>();
	private ImageView iv_share;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wordfuxi_android);
		init();
		initListener();
		initDate();
		initpop();
//		initRegisterBroadCast();
		
	}

	
	/**
	 * 注册广播
	 */
	private void initRegisterBroadCast() {
		
		
		IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(new TimingReceiver(), filter);
	}

	
	/**
	 * 断网计时广播接受者
	 * 
	 * @author Administrator
	 *
	 */
	class TimingReceiver extends BroadcastReceiver {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			
			  // 监听网络连接，包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
	        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
	            //获取联网状态的NetworkInfo对象
	            NetworkInfo info = intent
	                    .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
	            if (info != null) {
	                //如果当前的网络连接成功并且网络连接可用
	                if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
	                    if (info.getType() == ConnectivityManager.TYPE_WIFI
	                            || info.getType() == ConnectivityManager.TYPE_MOBILE) {
	                    	
	                    	Log.i("test", "网络重新连接");
	        				
	        				String gradeid = String.valueOf(lESSON_ID).substring(0, 4);
	        				HttpUtils httpUtils2 = new HttpUtils();
	        				httpUtils2.configCurrentHttpCacheExpiry(1000);
	        				httpUtils2.send(HttpMethod.GET,
	        						NetConstant.USERONLINE
	        								+ "InitInterfaceBegin.aspx?msg=1&type=3&account="
	        								+ SPUtils.getString(WordFuxiAndroidActivity.this, "account")
	        								+ "&gradeid=" + gradeid + "&lessonid=" + lESSON_ID,
	        						callBackTime);
	                    }
	                }
	            }
	        }
		}
	}
	
	
	private void init() {
		handler = new MyHandler(this);
		// cb_fuxi_collect = (CheckBox) findViewById(R.id.cb_fuxi_collect);
		cb_selecta = (CheckBox) findViewById(R.id.cb_selecta);
		cb_selectb = (CheckBox) findViewById(R.id.cb_selectb);
		bt_check = (Button) findViewById(R.id.bt_check);
		iv_content = (ImageView) findViewById(R.id.iv_content);
		iv_horn_a = (ImageView) findViewById(R.id.iv_horn_a);
		iv_horn_b = (ImageView) findViewById(R.id.iv_horn_b);
		iv_share = (ImageView) findViewById(R.id.iv_share);
		// tv_question_content = (TextView)
		// findViewById(R.id.tv_question_content);
		progress_bar = (ProgressBar) findViewById(R.id.progress_bar);
		gv_match = (GridView) findViewById(R.id.gv_match);
		tv_pager = (TextView) findViewById(R.id.tv_pager);
		tv_score = (TextView) findViewById(R.id.tv_score);
		ll_type1 = (LinearLayout) findViewById(R.id.ll_type1);
		ll_type2 = (LinearLayout) findViewById(R.id.ll_type2);
		tv_player = (TextView) findViewById(R.id.tv_player);
		tv_html_title = (TextView) findViewById(R.id.tv_html_title);
		tv_word_back = (TextView) findViewById(R.id.tv_word_back);
		tv_shoucang = (TextView) findViewById(R.id.tv_shoucang);
		tv_player_img = (TextView) findViewById(R.id.tv_player_img);
	}

	private void initListener() {
		bt_check.setOnClickListener(this);
		iv_horn_a.setOnClickListener(this);
		iv_horn_b.setOnClickListener(this);
		cb_selecta.setOnClickListener(this);
		cb_selectb.setOnClickListener(this);
		tv_shoucang.setOnClickListener(this);
//		tv_player.setOnClickListener(this);
		tv_word_back.setOnClickListener(this);
		iv_share.setOnClickListener(this);
	}

	private void initpop() {
		View contentView1 = LayoutInflater.from(this).inflate(
				R.layout.popup_true, null);
		View contentView2 = LayoutInflater.from(this).inflate(
				R.layout.popup_null2, null);
		View contentView3 = LayoutInflater.from(this).inflate(
				R.layout.popup_false, null);
		mPopWindow1 = new PopupWindow(contentView1,
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT, true);
		mPopWindow1.setContentView(contentView1);
		mPopWindow1.setBackgroundDrawable(new BitmapDrawable());
		mPopWindow1.setOutsideTouchable(true);

		mPopWindow2 = new PopupWindow(contentView2,
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT, true);
		mPopWindow2.setContentView(contentView2);
		mPopWindow2.setBackgroundDrawable(new BitmapDrawable());
		mPopWindow2.setOutsideTouchable(true);
		rootview = LayoutInflater.from(this).inflate(
				R.layout.activity_wordfuxi_android, null);

		mPopWindow3 = new PopupWindow(contentView3,
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT, true);
		mPopWindow3.setContentView(contentView3);

		mPopWindow3.setBackgroundDrawable(new BitmapDrawable());
		mPopWindow3.setOutsideTouchable(true);
	}

	private void initDate() {
		lESSON_ID = getIntent().getIntExtra("lESSON_ID", 0);
		lESSON_NAME = getIntent().getStringExtra("LESSON_NAME");

		tv_html_title.setText(lESSON_NAME);
		// http://192.168.0.198:6060/Test_Bank/UnitTest/GetLessonPreTestQuestion.aspx?lessonid=2001001&account=12212345678
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		final Request request = new Request.Builder()
				.url("http://m.moregolden.com:6060//Test_Bank/UnitTest/GetLessonPreTestQuestion.aspx?lessonid="
						+ lESSON_ID
						+ "&account="
						+ SPUtils.getString(this, ConfigConstant.USERNAME))
				.build();
		mOkHttpClient.newCall(request).enqueue(callback);

		randoms = getRandom(1);
	}

	Callback callback = new Callback() {

		@Override
		public void onFailure(Request arg0, IOException arg1) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onResponse(Response arg0) throws IOException {
			// TODO Auto-generated method stub
			String json = arg0.body().string();
			Log.e("yubo", json);
			Gson gson = new Gson();
			mFuxiExercisesBean = gson.fromJson(json, FuxiExercisesBean.class);
			question_count = mFuxiExercisesBean.question_list_count; // 题目数
			list = new ArrayList<FuxiExeQuelistDetail>();
			list = mFuxiExercisesBean.question_list; // 所有题目
			mAdapter = new MatchAdapter();
			Message message = Message.obtain();
			message.arg1 = 0;
			message.obj = mFuxiExercisesBean;
			handler.sendMessage(message);
		}
	};

	private FuxiExercisesBean mFuxiExercisesBean;

	public void UpdateUi(int questionNum2) {
		beginTimeMillis = System.currentTimeMillis();
		cb_selecta.setChecked(false);
		cb_selectb.setChecked(false);
		// tv_shoucang.setChecked(false);
//		tv_player.setText("");
		tv_player_img.setVisibility(tv_player_img.GONE);
		mPopWindow1.dismiss();
		mPopWindow2.dismiss();
		mPopWindow3.dismiss();

		isfavor = false;
		final String path = mFuxiExercisesBean.question_list.get(questionNum2).detail_list
				.get(2).detail_content;
//		Log.e("yubo", path);
		String text = mFuxiExercisesBean.question_list.get(questionNum2).question_type_name;
		String favor_status = "";
		if(mFuxiExercisesBean!=null&&mFuxiExercisesBean.question_list
				!=null&&mFuxiExercisesBean.question_list
						.get(questionNum2)!=null){
			favor_status = mFuxiExercisesBean.question_list
					.get(questionNum2).favor_status;
		}else{
			favor_status ="";
		}
		
		if ("1".equals(favor_status)) {
			isfavor = true;
			tv_shoucang.setBackgroundResource(R.drawable.nav_collect_ed2x);
			// tv_shoucang.setChecked(true);
		} else {
			isfavor = false;
			tv_shoucang.setBackgroundResource(R.drawable.nav_collect2x);
			// tv_shoucang.setChecked(false);
		}
		// tv_question_content.setText(text);
		if(path!=null && !"".equals(path)){
			Picasso.with(WordFuxiAndroidActivity.this).load(path)
			.into(iv_content);
		}
	}

	Boolean isfavor = false;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_share:
//			deleteShare();
			clickShare(v);

			break;

		case R.id.bt_check:
			bt_check.setClickable(false);
			if (!cb_selecta.isChecked() && !cb_selectb.isChecked()) {
				nullpopwindow();
			} else {
				endTimeMillis = System.currentTimeMillis();
				exercisesTime = new BigDecimal(
						(endTimeMillis - beginTimeMillis) / 1000.0).setScale(0,
						BigDecimal.ROUND_HALF_UP).intValue();
				judge();

				question_num++;
				question_type = list.get(question_num).question_type;
				message4 = null;
				message4 = Message.obtain();
//				Log.e("yubo", "question_type" + question_type);
				if ("11".equals(question_type)) {
					message4.what = 0;
				} else {
					message4.what = 1;
				}
				
				handler.sendMessageDelayed(message4, 1000);

			}
			
			break;
		case R.id.iv_horn_a:
			showToast(question_num, randoms[0]);
			break;
		case R.id.iv_horn_b:
			showToast(question_num, 1 - randoms[0]);
			break;
		case R.id.cb_selecta:
			if (cb_selectb.isChecked()) {
				cb_selectb.setChecked(false);
				cb_selecta.setChecked(true);
			}
			break;
		case R.id.cb_selectb:

			if (cb_selecta.isChecked()) {
				cb_selecta.setChecked(false);
				cb_selectb.setChecked(true);
			}
			break;
		case R.id.tv_shoucang:
			if (isfavor) {
				Toast.makeText(this, "取消", 0).show();
				isfavor = false;
				tv_shoucang.setBackgroundResource(R.drawable.nav_collect2x);
				// http://192.168.0.198:8080/User_Manage/UserFavor/CancelUserQuestion.aspx?account=12212345678&lessonid=1001001&questionid=1&exam_type=1
				OkHttpClient mOkHttpClient = new OkHttpClient();
				// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				int questionid = question_num + 1;
				final Request request = new Request.Builder()
						.url("http://m.moregolden.com:8080/User_Manage/UserFavor/CancelUserQuestion.aspx?lessonid="
								+ lESSON_ID
								+ "&account="
								+ SPUtils.getString(this,
										ConfigConstant.USERNAME)
								+ "&questionid=" + questionid + "&exam_type=2")
						.build();
				mOkHttpClient.newCall(request).enqueue(callbackcollect);

			} else {
				Toast.makeText(this, "收藏", 0).show();
				isfavor = true;
				tv_shoucang.setBackgroundResource(R.drawable.nav_collect_ed2x);
				// http://192.168.0.198:8080/User_Manage/UserFavor/SaveUserQuestion.aspx?account=12212345678&lessonid=1001001&questionid=1&exam_type=1
				OkHttpClient mOkHttpClient = new OkHttpClient();
				// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				int questionid = question_num + 1;
				final Request request = new Request.Builder()
						.url("http://m.moregolden.com:8080/User_Manage/UserFavor/SaveUserQuestion.aspx?lessonid="
								+ lESSON_ID
								+ "&account="
								+ SPUtils.getString(this,
										ConfigConstant.USERNAME)
								+ "&questionid=" + questionid + "&exam_type=2")
						.build();
				mOkHttpClient.newCall(request).enqueue(callbackcollect);
			}
			// if (isChecked) {
			// //
			// http://192.168.0.198:8080/User_Manage/UserFavor/SaveUserQuestion.aspx?account=12212345678&lessonid=1001001&questionid=1&exam_type=1
			// OkHttpClient mOkHttpClient = new OkHttpClient();
			// //
			// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			// int questionid=question_num+1;
			// final Request request = new Request.Builder()
			// .url("http://192.168.0.249:8080/User_Manage/UserFavor/SaveUserQuestion.aspx?lessonid=2001001&account=15098012693&questionid="+questionid+"&exam_type=2")
			// .build();
			// mOkHttpClient.newCall(request).enqueue(callbackcollect);
			// }else{
			//
			// }
			break;
		case R.id.tv_player: // 音频播放按钮
			for (int i = 0; i < mFuxiExercisesBean.question_list
					.get(question_num).detail_list.size(); i++) {
				String answer = mFuxiExercisesBean.question_list
						.get(question_num).question_answer;
				Log.e("yubo",
						"detail_content="
								+ mFuxiExercisesBean.question_list
										.get(question_num).detail_list.get(i).detail_content);
				if (mFuxiExercisesBean.question_list.get(question_num).detail_list
						.get(i).detail_content.contains(answer)) {
					showToast(question_num, i);
				}
			}

			break;
		case R.id.tv_word_back:
			finish();
			break;
		default:
			break;
		}
	}

	private void judge() {
		String answer = mFuxiExercisesBean.question_list.get(question_num).question_answer;
		String select;
		if (cb_selecta.isChecked()) {
			select = mFuxiExercisesBean.question_list.get(question_num).detail_list
					.get(randoms[0]).detail_content;
			UploadScoreBean mUploadScoreBean1;
			if (select.contains(answer)) {
				truepopwindow();
				score += 10;
				mUploadScoreBean1 = new UploadScoreBean(exercisesTime, 0,
						question_num + 1, 11);
//				Log.e("yubo", "exercisesTime=" + exercisesTime);
			} else {
				falsepopwindow();
				mUploadScoreBean1 = new UploadScoreBean(exercisesTime, 1,
						question_num + 1, 11);
//				Log.e("yubo", "exercisesTime=" + exercisesTime);
			}

			 UploadScorelist.add(mUploadScoreBean1);

		} else if (cb_selectb.isChecked()) {
			select = mFuxiExercisesBean.question_list.get(question_num).detail_list
					.get(1 - randoms[0]).detail_content;
			UploadScoreBean mUploadScoreBean1;
			if (answer!=null&&select!=null&&select.contains(answer)) {
				truepopwindow();
				score += 10;
				mUploadScoreBean1 = new UploadScoreBean(exercisesTime, 0,
						question_num + 1, 11);
//				Log.e("yubo", "exercisesTime=" + exercisesTime);
			} else {
				falsepopwindow();
				mUploadScoreBean1 = new UploadScoreBean(exercisesTime, 1,
						question_num + 1, 11);
//				Log.e("yubo", "exercisesTime=" + exercisesTime);
			}
			UploadScorelist.add(mUploadScoreBean1);
		}
	}

	private MediaPlayer mediaPlayer = new MediaPlayer();
	private int[] randoms;

	public void showToast(int toast, int order) {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
//			System.gc();
			// mediaPlayer = new MediaPlayer();
		}
//		Log.e("yubo", "toast===" + toast);
		if(mFuxiExercisesBean.question_list!=null){
			try {
				String uri = mFuxiExercisesBean.question_list.get(toast).detail_list
						.get(order).detail_content;
			
			
		
		
		// Toast.makeText(mContext, toast, 0).show();
		// if ("http".equals(toast.substring(0, 4))) {
		// uri = toast;
		// } else {
		// uri = NetConstant.H5 + "html5/" + toast;
		// }
//		Log.e("yubo", "uri===" + uri);
		if (mediaPlayer == null) {
			// SoundPool sp = new
			// SoundPool(10,AudioManager.STREAM_SYSTEM,0);
			// sp.load(path, priority);
			mediaPlayer = MediaPlayer.create(WordFuxiAndroidActivity.this,
					Uri.parse(uri));
		}
			} catch (Exception e) {
				// TODO: handle exception
			}
		try {
			// mediaPlayer.reset();
			// mediaPlayer.setDataSource(uri);
			// mediaPlayer.prepare();
			mediaPlayer.start();

			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					// TODO Auto-generated method stub
					Log.e("yubo", "uri===setOnCompletionListener");
					mediaPlayer.stop();
					mediaPlayer.release();
					mediaPlayer = null;
//					System.gc();
				}
			});
			// mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
			//
			// @Override
			// public void onPrepared(MediaPlayer mp) {
			// // TODO Auto-generated method stub
			// mediaPlayer.start();
			//
			// }
			// });

		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}

	private int[] getRandom(int n) {
		int[] randoms = new int[n];

		Vector<Integer> vector = new Vector<Integer>();
		for (int i = 0; i < n; i++) {
			int random = (int) (Math.random() * n);
			while (vector.contains(random)) {
				random = (int) (Math.random() * n);
			}
			Log.i("bitmapActivity", "int[" + i + "]=" + String.valueOf(random));

			vector.add(random);
			randoms[i] = random;

		}

		return randoms;
	}

	Callback callbackcollect = new Callback() {


		@Override
		public void onFailure(Request arg0, IOException arg1) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onResponse(Response arg0) throws IOException {
			// TODO Auto-generated method stub
			
		}

	
	};
	private String lESSON_NAME;
	private long beginTimeMillis;
	private long endTimeMillis;
	private int exercisesTime;

	private void falsepopwindow() {

		mPopWindow3.showAtLocation(rootview, Gravity.CENTER, 0, 0);
		String path = "http://m.moregolden.com:8080/html5/mp3/errorMp3.mp3";
		showToast(path);
	}

	private void truepopwindow() {

		mPopWindow1.showAtLocation(rootview, Gravity.CENTER, 0, 0);

		String path = "http://m.moregolden.com:8080/html5/mp3/rightMp3.mp3";
		showToast(path);

	}

	private void nullpopwindow() {

		mPopWindow2.showAtLocation(rootview, Gravity.CENTER, 0, 0);
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				bt_check.setClickable(true);
				mPopWindow2.dismiss();
			}
		}, 1000);
	}

	class MatchAdapter extends BaseAdapter {

		public int getCount() {

			return detaillist.size();
		}

		public Object getItem(int position) {

			return null;
		}

		public long getItemId(int position) {

			return 0;
		}

		ViewHolder vh = null;

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(parent.getContext(),
						R.layout.item_match, null);
				vh = new ViewHolder();
				vh.tv_word = (TextView) convertView.findViewById(R.id.tv_word);
				convertView.setTag(vh);
			} else {
				vh = (ViewHolder) convertView.getTag();
			}
			// Log.e("yubo", list.get(8).detail_list.get(0).question_content);
			vh.tv_word
					.setText(list.get(question_num).detail_list.get(position).question_content);

			if (isContainChinese(detaillist.get(position).question_content)) {
				vh.tv_word
						.setBackground(WordFuxiAndroidActivity.this
								.getResources().getDrawable(
										R.drawable.shape_blue_word));
			} else {

				vh.tv_word.setBackground(WordFuxiAndroidActivity.this
						.getResources().getDrawable(
								R.drawable.shape_purple_word));
			}
			return convertView;
		}

		class ViewHolder {
			private TextView tv_word;
		}
	}

	int totalTime = 0;

	public class MyHandler extends Handler {

		private final WeakReference<WordFuxiAndroidActivity> mActivity;

		public MyHandler(WordFuxiAndroidActivity activity) {
			mActivity = new WeakReference<WordFuxiAndroidActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			WordFuxiAndroidActivity activity = mActivity.get();
			if (activity == null) {
				super.handleMessage(msg);
				return;
			}
			mPopWindow1.dismiss();
			mPopWindow2.dismiss();
			mPopWindow3.dismiss();
			switch (msg.what) {
			case 0: // 题型1
				bt_check.setClickable(true);
				progress_bar.setProgress(question_num);
				tv_score.setText(score + ".0分");
				tv_pager.setText((question_num + 1) + "/" + question_count);
				tv_shoucang.setText((question_num + 1) + ""); // 收藏
				
				if(question_num==0){
					tv_score.setText(score + "分");
				}
				
				UpdateUi(question_num);
				break;
			case 1: // 题型2
				beginTimeMillis = System.currentTimeMillis();
				isfavor = false;
				progress_bar.setProgress(question_num); // 进度条
				tv_player_img.setVisibility(tv_player_img.GONE);// 喇叭
				tv_score.setText(score + ".0分"); // 成绩
				ll_type1.setVisibility(ll_type1.GONE);
				ll_type2.setVisibility(ll_type2.VISIBLE);
				// tv_text.setVisibility(tv_text.GONE);
				tv_pager.setText((question_num + 1) + "/" + question_count);// 题号
				tv_shoucang.setText((question_num + 1) + ""); // 收藏
				tv_player.setText(list.get(question_num).question_type_name);
				tv_player.setClickable(false);

				String favor_status = mFuxiExercisesBean.question_list
						.get(question_num).favor_status;
				if ("1".equals(favor_status)) {
					isfavor = true;
					tv_shoucang
							.setBackgroundResource(R.drawable.nav_collect_ed2x);
					// tv_shoucang.setChecked(true);
				} else {
					isfavor = false;
					tv_shoucang.setBackgroundResource(R.drawable.nav_collect2x);
					// tv_shoucang.setChecked(false);
				}

				detaillist = list.get(question_num).detail_list;
				dismissedlist = new ArrayList<Integer>();
				dismissedlist.add(-1);

				if (list.get(question_num).detail_list.size() > 11) {

					if (!detaillist.isEmpty()) {
						for (int i = 0; i < detaillist.size(); i++) {
							for (int j = i + 1; j < detaillist.size(); j++) {
								if(i<detaillist.size()&&j<detaillist.size()){
									if (detaillist.get(i).question_content.equals(detaillist
											.get(j).question_content)) {
										detaillist.remove(j);
									}
								}
							}
						}
					}
				}
				gv_match.setAdapter(mAdapter);
				gv_match.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						for (int i = 0; i < dismissedlist.size(); i++) {
							if (dismissedlist.get(i) == position) {
								return;
							}
						}

						if (Click == 1) { // 第1次点击

							tv_word1 = (TextView) view
									.findViewById(R.id.tv_word);

							word1 = tv_word1.getText().toString();
							Log.e("yubo", "tv_word1=" + word1);
							if (isContainChinese(word1)) {// 判断
								ClickType1 = 0; // 汉字
							} else {
								ClickType1 = 1; // 英文
							}
							
							tv_word1.setBackground(WordFuxiAndroidActivity.this
									.getResources().getDrawable(
											R.drawable.shape_red_word));
							Click++;
							p = position;

						} else if (Click == 2) { // 第2次点击
							if (p != position) {
								tv_word2 = (TextView) view
										.findViewById(R.id.tv_word);
								word2 = tv_word2.getText().toString();
								Log.e("yubo", "tv_word2=" + word2);
								if (isContainChinese(word2)) {
									ClickType2 = 0;
								} else {
									ClickType2 = 1;
								}

								if (ClickType1 == ClickType2) {
									Click = 2;
									p = position;

									if (isContainChinese(word1)) {
										tv_word1.setBackground(WordFuxiAndroidActivity.this
												.getResources()
												.getDrawable(
														R.drawable.shape_blue_word));
									} else {
										tv_word1.setBackground(WordFuxiAndroidActivity.this
												.getResources()
												.getDrawable(
														R.drawable.shape_purple_word));
									}
									tv_word1 = (TextView) view
											.findViewById(R.id.tv_word);
									word1 = tv_word1.getText().toString();

									tv_word1.setBackground(WordFuxiAndroidActivity.this
											.getResources().getDrawable(
													R.drawable.shape_red_word));
									return;
								}

								gv_match.setClickable(false);
								Click = 1;
//								Log.e("yubo",
//										"tv_word1=cece="
//												+ list.get(position).question_answer);
								if (word1.equals(detaillist.get(position).question_answer)) {
									truepopwindow();
									tv_word1.setVisibility(tv_word1.INVISIBLE);
									tv_word2.setVisibility(tv_word2.INVISIBLE);
									dismissedlist.add(p);
									dismissedlist.add(position);
								} else {
									falsepopwindow();
									alltrue = 1;
									tv_word1.setVisibility(tv_word1.INVISIBLE);
									tv_word2.setVisibility(tv_word2.INVISIBLE);
									dismissedlist.add(p);
									dismissedlist.add(position);
								}
								UploadScoreBean mUploadScoreBean;
								if (dismissedlist.size() > detaillist.size()) { // 全部消除完
									endTimeMillis = System.currentTimeMillis();
									exercisesTime = new BigDecimal(
											(endTimeMillis - beginTimeMillis) / 1000.0)
											.setScale(0,
													BigDecimal.ROUND_HALF_UP)
											.intValue();

									if (alltrue == 0) {
										score += 10;
										mUploadScoreBean = new UploadScoreBean(
												exercisesTime, 0,
												question_num + 1, 2);
									} else {

										mUploadScoreBean = new UploadScoreBean(
												exercisesTime, 1,
												question_num + 1, 2);
									}
									UploadScorelist.add(mUploadScoreBean);
									alltrue = 0;
									question_num++;

									if (question_num < question_count) {

										question_type = list.get(question_num).question_type;

										Message message = Message.obtain();
										if ("2".equals(question_type)) {
											message.what = 1;
										} else if ("3".equals(question_type)) {
											message.what = 2;
										}
										handler.sendMessageDelayed(message,
												1000);
									} else {
										tv_score.setText(score + ".0分"); // 成绩

										for (UploadScoreBean i : UploadScorelist) {
											totalTime += i.qa_time;
										}

										handler.postDelayed(new Runnable() {

											@Override
											public void run() {
												// TODO Auto-generated method
												// stub
												NormalDialogCustomAttr();

											}
										}, 1000);

									}
								}

								postDelayed(new Runnable() {
									@Override
									public void run() {
										gv_match.setClickable(true);
										mPopWindow1.dismiss();
										mPopWindow2.dismiss();
										mPopWindow3.dismiss();
									}
								}, 1000);

							} else {// 重复点击
								Click = 1;
								word1 = tv_word1.getText().toString();
								if (isContainChinese(word1)) {
									tv_word1.setBackground(WordFuxiAndroidActivity.this
											.getResources().getDrawable(
													R.drawable.shape_blue_word));
								} else {
									tv_word1.setBackground(WordFuxiAndroidActivity.this
											.getResources()
											.getDrawable(
													R.drawable.shape_purple_word));
								}
							}
						}
					}
				});

				break;

			default:
				super.handleMessage(msg);
				break;
			}
		}
	}

	// 是否包含汉字
	public static boolean isContainChinese(String str) {

		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			return true;
		}
		return false;
	}

	
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET, NetConstant.USERONLINE
				+ "SaveInterfaceEnd.aspx?msg=1&rid=" + rid + "&account="
				+ SPUtils.getString(this, ConfigConstant.USERNAME),
				callBackTimefinish);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		beginTimeMillis = System.currentTimeMillis();
		String gradeid = String.valueOf(lESSON_ID).substring(0, 4);
		HttpUtils httpUtils2 = new HttpUtils();
		httpUtils2.configCurrentHttpCacheExpiry(1000);
		httpUtils2.send(HttpMethod.GET,
				NetConstant.USERONLINE
						+ "InitInterfaceBegin.aspx?msg=1&type=2&account="
						+ SPUtils.getString(this, ConfigConstant.USERNAME)
						+ "&gradeid=" + gradeid + "&lessonid=" + lESSON_ID,
				callBackTime);
	}

	public void deleteShare() {

		File f = new File(getSDPath() + "/goldupload/");

		File[] fl = f.listFiles();
		for (int i = 0; i < fl.length; i++) {
			if (fl[i].toString().endsWith("out.jpg")
					|| fl[i].toString().endsWith("out.jpg")) {
				if (fl[i].delete()) {
				} else {
				}
			}
		}
	}

	public void clickShare(View v) {
		// 得到当前view所在view结构中的根view
		View vv = v.getRootView();
		// 设置属性
		vv.setDrawingCacheEnabled(true);

		// 取得位图
		Bitmap bm = vv.getDrawingCache();

		Resources res = getResources();
		Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.ycsjlogo);
		Bitmap watermarkBitmap = watermarkBitmap(
				bm,
				bmp,
				"金牌君使用者："
						+ SPUtils.getString(WordFuxiAndroidActivity.this,
								"name"));
		// iv.setImageBitmap(watermarkBitmap);
		try {
			saveFile(watermarkBitmap, "out.jpg");
			sharePic();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		vv.destroyDrawingCache();
	}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	public void saveFile(Bitmap bm, String fileName) throws IOException {
		String path = getSDPath() + "/goldupload/";
		File dirFile = new File(path);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}

		File myCaptureFile = new File(path + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
	}

	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		} else {
			sdDir = getFilesDir();
		}
		return sdDir.toString();
	}

	/**
	 * 加水印 也可以加文字
	 * 
	 * @param src
	 * @param watermark
	 * @param title
	 * @return
	 */
	public static Bitmap watermarkBitmap(Bitmap src, Bitmap watermark,
			String title) {
		if (src == null) {
			return null;
		}
		int w = src.getWidth();
		int h = src.getHeight();
		// 需要处理图片太大造成的内存超过的问题,这里我的图片很小所以不写相应代码了

		Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
		Canvas cv = new Canvas(newb);
		cv.drawBitmap(src, 0, 0, null);// 在 0，0坐标开始画入src
		Paint paint = new Paint();
		// 加入图片
		if (watermark != null) {
			int ww = watermark.getWidth();
			int wh = watermark.getHeight();
			// paint.setAlpha(50);
			cv.drawBitmap(watermark, w - ww - 5, h * 3 / 4, paint);// 在src的右下角画入水印
			// cv.drawBitmap(watermark, 0, 0, paint);// 在src的左上角画入水印
		} else {
			Log.i("i", "water mark failed");
		}
		// 加入文字
		if (title != null) {
			String familyName = "宋体";
			Typeface font = Typeface.create(familyName, Typeface.NORMAL);
			TextPaint textPaint = new TextPaint();
			textPaint.setColor(Color.RED);
			// textPaint.setAlpha(52);
			textPaint.setTypeface(font);
			textPaint.setTextSize(24);
			// 这里是自动换行的
			// StaticLayout layout = new
			// StaticLayout(title,textPaint,w,Alignment.ALIGN_OPPOSITE,1.0F,0.0F,true);
			// layout.draw(cv);
			// 文字就加左上角算了
			cv.drawText(title, w / 5, h * 7 / 8, textPaint);
		}
		cv.save(Canvas.ALL_SAVE_FLAG);// 保存
		cv.restore();// 存储
		return newb;
	}

	public void sharePic() {
		// ShareSDK.initSDK(WordsFuxiActivity.this);
		MobSDK.init(WordFuxiAndroidActivity.this, "12c24ea0b59b0",
				"aae63565fbd69b1acbfcdd0d5ac0b35c");
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

			@Override
			public void onShare(Platform platform, ShareParams paramsToShare) {
				 if (SinaWeibo.NAME.equals(platform.getName())) {
					paramsToShare.setText("");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					// paramsToShare.setImageUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					paramsToShare.setImagePath(getSDPath()
							+ "/goldupload/out.jpg");// 确保SDcard下面存在此张图片
				} else if (QQ.NAME.equals(platform.getName())) {
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					paramsToShare.setImagePath(getSDPath()
							+ "/goldupload/out.jpg");// 确保SDcard下面存在此张图片
					// oks.seti
					// url仅在微信（包括好友和朋友圈）中使用
					// oks.setUrl(list.get(0).WEB_URL);
					// 微信分享必须设置否则发送文本信息
					// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare
							.setSiteUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");

				} else {
					paramsToShare.setShareType(Platform.SHARE_IMAGE);
					paramsToShare.setTitle("wer");
					// paramsToShare.setText("ces");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					paramsToShare.setImagePath(getSDPath()
							+ "/goldupload/out.jpg");// 确保SDcard下面存在此张图片
					// paramsToShare.setUrl("http://www.baidu.com");
					// paramsToShare.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
					// oks.seti
					// url仅在微信（包括好友和朋友圈）中使用
					// oks.setUrl(list.get(0).WEB_URL);
					// 微信分享必须设置否则发送文本信息
					// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					// paramsToShare.setComment("");
					// // site是分享此内容的网站名称，仅在QQ空间使用
					// paramsToShare.setSite(getString(R.string.app_name));
					// // siteUrl是分享此内容的网站地址，仅在QQ空间使用
					// paramsToShare.setSiteUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");

				}

			}
		});
		// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		// oks.setTitle(getString(R.string.share));
		// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
		// oks.setTitleUrl("http://139.129.57.83:8080/Appandroid/APPicon192.png");

		// text是分享文本，所有平台都需要这个字段
		// oks.setText("看视频学英语,名师上课超有用哦!");

		// 启动分享GUI
		oks.show(WordFuxiAndroidActivity.this);
	}

	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;

	public void setBasIn(BaseAnimatorSet bas_in) {
		this.bas_in = bas_in;
	}

	public void setBasOut(BaseAnimatorSet bas_out) {
		this.bas_out = bas_out;
	}

	private void NormalDialogCustomAttr() {
		final NormalDialog dialog = new NormalDialog(this);
		dialog.content("是否提交该考试成绩").btnText("取消", "确定")//
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(23)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

			@Override
			public void onBtnLeftClick() {

				finish();

			}
		});
		dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

			@Override
			public void onBtnRightClick() {
				
				String c = SPUtil.getString(WordFuxiAndroidActivity.this, "account", "");
				if(TextUtils.isEmpty(c)){
					dialog.dismiss();
					Intent intent = new Intent(WordFuxiAndroidActivity.this,
							LoginActivity.class);
					startActivity(intent);
					finish();
				}else{
				
				Gson gson = new Gson();
				String json = gson.toJson(UploadScorelist);
				Intent intent = new Intent(WordFuxiAndroidActivity.this,
						ScoreSubmitActivity.class);
				intent.putExtra("Score", score);
				intent.putExtra("totalTime", totalTime);
				intent.putExtra("Uploadjson", json);
				intent.putExtra("lESSON_ID", ""+lESSON_ID);
				intent.putExtra("LESSON_NAME", lESSON_NAME);
				intent.putExtra("exam_type", "2");

				startActivity(intent);
				dialog.dismiss();
				finish();
				}
			}
		});
	}

	public void showToast(String toast) {
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
			System.gc();
			// mediaPlayer = new MediaPlayer();
		}

		String uri = toast;

		if (mediaPlayer == null) {
			// SoundPool sp = new
			// SoundPool(10,AudioManager.STREAM_SYSTEM,0);
			// sp.load(path, priority);
			mediaPlayer = MediaPlayer.create(WordFuxiAndroidActivity.this,
					Uri.parse(uri));
		}
		try {
			// mediaPlayer.reset();
			// mediaPlayer.setDataSource(uri);
			// mediaPlayer.prepare();
			mediaPlayer.start();

			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					// TODO Auto-generated method stub
					Log.e("yubo", "uri===setOnCompletionListener");
					mediaPlayer.stop();
					mediaPlayer.release();
					mediaPlayer = null;
					System.gc();
				}
			});
			// mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
			//
			// @Override
			// public void onPrepared(MediaPlayer mp) {
			// // TODO Auto-generated method stub
			// mediaPlayer.start();
			//
			// }
			// });

		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	
	private String rid;
	private RequestCallBack<String> callBackTime = new RequestCallBack<String>() {
		

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			// TODO Auto-generated method stub
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象

			// Log.i("testtime","wordfuxiresum"+ json.toString());

			Gson gson = new Gson();
			timeresq fromJson = gson.fromJson(json, timeresq.class);
			rid = fromJson.rid;

			Log.e("test", "rid===" + rid);
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			// TODO Auto-generated method stub
			rid = "";
		}
	};
	
	private RequestCallBack<String> callBackTimefinish = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			// TODO Auto-generated method stub
			String json = responseInfo.result;
			// 使用Gson把json解析成对象
			// 1 得到gson对象

			// Log.i("testtime","wordfuxionpause"+ json.toString());
		}

		@Override
		public void onFailure(HttpException error, String msg) {

		}
	};
}
